<template>
  <div class="update-avatar">
    <img :src="img" ref="image" />
    <div class="toolbar">
      <span @click="$emit('close')">取消</span>
      <span @click="changeavatorFn">完成</span>
    </div>
  </div>
</template>

<script>
import 'cropperjs/dist/cropper.css'
import Cropper from 'cropperjs'
import { updataUserAvator } from '@/api/login'
export default {
  props: {
    img: {
      type: [String, Object]
    }
  },
  data () {
    return {
      cropper: ''
    }
  },
  mounted () {
    this.cropperFn()
  },
  methods: {
    cropperFn () {
      const image = this.$refs.image
      this.cropper = new Cropper(image, {
        // 实例对象
        viewMode: 1, // 只能在裁剪的图片范围内移动
        dragMode: 'move', // 画布和图片都可以移动
        aspectRatio: 1, // 裁剪区默认正方形
        autoCropArea: 1, // 自动调整裁剪图片
        cropBoxMovable: false, // 禁止裁剪区移动
        cropBoxResizable: false, // 禁止裁剪区缩放
        background: false // 关闭默认背景
      })
    },
    changeavatorFn () {
      this.cropper.getCroppedCanvas().toBlob(async (blob) => {
        this.$toast.loading({
          message: '加载中...',
          forbidClick: true,
          duration: 0
        })
        try {
          const formData = new FormData()
          formData.append('photo', blob) // 请求的参数为file类型的
          const {
            data: {
              data: { photo }
            }
          } = await updataUserAvator(formData)
          // 关闭弹层
          this.$emit('close', photo)
          this.$toast.success('修改成功')
        } catch (error) {
          this.$toast.fail('修改失败')
        }
      })
    }
  }
}
</script>

<style scoped lang="less">
.update-avatar {
  background: rgba(0, 0, 0, 0.8);
  width: 100%;
  height: 100%;
  img {
    width: 100%;
  }
  .toolbar {
    position: fixed;
    bottom: 10px;
    width: 100%;
    display: flex;
    justify-content: space-between;
    font-size: 28px;
    color: #fff;
    padding: 0 15px;
    box-sizing: border-box;
  }
}
</style>
